// 导入数据库操作模块
const { use } = require("express/lib/application");
const db = require("../db/index");
const { v4: uuidv4 } = require('uuid');


//获取用户信息
exports.getCaidanList = (req, res) => {

    const query = 'SELECT * FROM caidan';

    db.query(query, (err, results) => { // 将 id 作为查询参数传递
        if (err) {
            console.error('查询失败:', err);
            return res.status(500).send('数据库查询失败');
        }
        // 树形结构
           const buildMenuTree = (menuItems, parentId = null) => {
            console.log(menuItems,"传进来的值")
            const tree = [];
            menuItems.forEach(item => {
                console.log(item.parentId)
              if (item.parentId === parentId) {
                const children = buildMenuTree(menuItems, item.caidanId);
                if (children.length) {
                  item.children = children;
                } else {
                  item.children = [];
                }
                tree.push(item);
              }
            });
            return tree;
          };


           const menuTree = buildMenuTree(results);
        //    返回数据
           res.status(200).json(menuTree);

    });
};
// 添加用户
exports.addMenu = (req, res) => {
    console.log(req.body)

    const menuInfo = req.body
    menuInfo.caidanId = uuidv4()

    const parentId = menuInfo.parentId[menuInfo.parentId.length - 1]
    menuInfo.parentId = parentId
    console.log(parentId)
    console.log(menuInfo.caidanId )
    console.log(menuInfo,"请求了添加菜单借口")

    const query = 'INSERT INTO caidan (name,path,type,state,caidanId,parentId) VALUES(?,?,?,?,?,?)'
    db.query(query,[menuInfo.name,menuInfo.path,menuInfo.type,menuInfo.state,menuInfo.caidanId,menuInfo.parentId],(err,results)=>{
        if (err) {
            console.error('查询失败:', err);
            return res.status(500).send('数据库查询失败');
        }
        // 返回查询结果
        res.status(200).json(results);
        console.log(results)
    })
};
// 删除用户
exports.deleteMenu = (req, res) => {
    console.log(req.body)
    console.log("请求了删除菜单接口")
    const menuInfo = req.body
    const query = ' DELETE FROM caidan  WHERE caidanId=?'
    db.query(query,menuInfo.caidanId,(err,results)=>{
        if (err) {
            console.error('查询失败:', err);
            return res.status(500).send('数据库查询失败');
        }
        // 返回查询结果
        res.status(200).json(results);
        console.log(results)
    })
};
// // 修改用户信息
// exports.updateUser = (req, res) =>{
//     console.log('请求了修改用户信息的借口')
//     const userInfo = req.body
//     console.log(userInfo)
//     const query = "UPDATE Users SET username=?, password=?,state=?  WHERE id=?"
//     db.query(query,[userInfo.username,userInfo.password,userInfo.state, userInfo.id],(err, results)=>{
//         if (err) {
//             console.error('查询失败:', err);
//             return res.status(500).send('数据库查询失败');
//         }
//         // 返回查询结果
//         res.status(200).json(results);
//         console.log(results)
//     })
// }

